package com.wbdgj.ui.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.google.zxing.WriterException;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.model.ResultUrlModel;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.uitool.ShareBoard;
import com.wbdgj.ui.uitool.ShareBoardlistener;
import com.wbdgj.ui.uitool.SnsPlatform;
import com.wbdgj.utils.QRCodeUtil;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.facebook.Facebook;
import cn.jiguang.share.facebook.messenger.FbMessenger;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.twitter.Twitter;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jiguang.share.weibo.SinaWeiboMessage;
import retrofit2.Call;

public class YhqDetailMyActivity extends BaseActivity{

    private Context context = this;
    @BindView(R.id.ewmImg)
    ImageView ewmImg;
    @BindView(R.id.txmImg)
    ImageView txmImg;
    @BindView(R.id.qid)
    TextView qid;

    @BindView(R.id.AMOUNT)
    TextView AMOUNTTxt;
    @BindView(R.id.DESCRIBES)
    TextView DESCRIBESTxt;
    @BindView(R.id.ABLE_BRANCH_NAME)
    TextView ABLE_BRANCH_NAMETxt;
    @BindView(R.id.tv_topTitle)
    TextView tv_topTitle;

    @BindView(R.id.text_top_right)
    TextView text_top_right;

    private static final int REQUEST_PERMISSION = 0;
    private String id;
    private String urlStr;
    private int mAction = Platform.ACTION_SHARE;
    private ShareBoard mShareBoard;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
//            if (progressDialog != null && progressDialog.isShowing()) {
//                progressDialog.dismiss();
//            }
        }
    };

    private  String AMOUNT, MIN_AMOUNT, ABLE_BRANCH_NAME, NAME, BRANCH_NAME, DESCRIBES;
    private String USE_BEG, USE_END, BRANCH_ID;
    @Override
    protected int getLayoutResId() {
        return R.layout.ui_wb_yhq_my_detail;
    }

    @Override
    protected void initView() {
        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission ) {
            requestPermission();
        }
        id = getIntent().getStringExtra("id");
        AMOUNT = getIntent().getStringExtra("AMOUNT");
        MIN_AMOUNT = getIntent().getStringExtra("MIN_AMOUNT");
        ABLE_BRANCH_NAME = getIntent().getStringExtra("ABLE_BRANCH_NAME");
        NAME = getIntent().getStringExtra("NAME");
        BRANCH_NAME = getIntent().getStringExtra("BRANCH_NAME");
        DESCRIBES = getIntent().getStringExtra("DESCRIBES");
        USE_BEG = getIntent().getStringExtra("USE_BEG");
        USE_END = getIntent().getStringExtra("USE_END");
        BRANCH_ID = getIntent().getStringExtra("BRANCH_ID");
        if (AMOUNT.equals("0")){
            AMOUNTTxt.setVisibility(View.GONE);
        }else{
            AMOUNTTxt.setVisibility(View.VISIBLE);
        }
//        if (DESCRIBES.equals("")){
//            DESCRIBESTxt.setVisibility(View.GONE);
//        }else{
//            DESCRIBESTxt.setVisibility(View.VISIBLE);
//        }
//        if (ABLE_BRANCH_NAME.equals("null")){
//            ABLE_BRANCH_NAMETxt.setText("可用门店:"+BRANCH_NAME);
//        }else{
//            ABLE_BRANCH_NAMETxt.setText("可用门店:"+ABLE_BRANCH_NAME);
//        }
        AMOUNTTxt.setText("优惠金额:"+AMOUNT+"元(消费满"+MIN_AMOUNT+"元可用)");
        DESCRIBESTxt.setText("备注:"+DESCRIBES);
        tv_topTitle.setText(NAME);
        qid.setText(id);
        try {
            // 根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（310*310）
            Bitmap bitmapQRCode = QRCodeUtil.createQRCode(id+"",
                    510);
            ewmImg.setImageBitmap(bitmapQRCode);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        txmImg.setImageBitmap(QRCodeUtil.creatBarcode(
                getApplicationContext(), id+"", 100, 30, false));

        findViewById(R.id.text_top_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(context,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(YhqDetailMyActivity.this
                            , new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
                    ToastUtils.toastShort("请打开您设备上的照片,媒体内容和文件访问权限!");
                    return;
                }
                appCouponcreateUrl();
            }
        });

        findViewById(R.id.ABLE_BRANCH_NAME).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(context, YhqDetailMyGaginActivity.class).putExtra("ABLE_BRANCH_NAME", ABLE_BRANCH_NAME)
                        .putExtra("BRANCH_NAME", BRANCH_NAME)
                        .putExtra("USE_BEG", USE_BEG)
                        .putExtra("USE_END", USE_END)
                        .putExtra("DESCRIBES", DESCRIBES));

            }
        });

        permit();

        findViewById(R.id.qwmdImg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(context, WbDetailActivity.class).putExtra("id", BRANCH_ID).putExtra("DISTANCE", ""));
            }
        });
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }


    private void appCouponcreateUrl() {
        Call<ResultUrlModel> call = HttpAdapter.getSerives().appCouponcreateUrl(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), id);
        call.enqueue(new OnResponseListener<ResultUrlModel>(context) {
            @Override
            protected void onSuccess(ResultUrlModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    urlStr = HttpAdapter.HEAD_URL + userModelBaseResultModel.getUrl();
                    mAction = Platform.ACTION_SHARE;
                    showBroadView();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void showBroadView() {
        if (mShareBoard == null) {
            mShareBoard = new ShareBoard(this);
            List<String> platforms = JShareInterface.getPlatformList();
            if (platforms != null) {
                Iterator var2 = platforms.iterator();
                while (var2.hasNext()) {
                    String temp = (String) var2.next();
                    SnsPlatform snsPlatform = createSnsPlatform(temp);
                    mShareBoard.addPlatform(snsPlatform);
                }
            }
            mShareBoard.setShareboardclickCallback(mShareBoardlistener);
        }
        mShareBoard.show();
    }

    private ShareBoardlistener mShareBoardlistener = new ShareBoardlistener() {
        @Override
        public void onclick(SnsPlatform snsPlatform, String platform) {

            switch (mAction) {
                case Platform.ACTION_SHARE:
//                    progressDialog.show();
                    //这里以分享链接为例
                    ShareParams shareParams = new ShareParams();
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setTitle("我正在使用全城VIP转赠优惠券，快来领取吧！");
                    shareParams.setText("领取优惠券");
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setUrl(urlStr);
//                    shareParams.setUrl("http://www.ahxfk.com/");
                    shareParams.setImagePath(BaseApplication.ImagePath);
                    JShareInterface.share(platform, shareParams, mShareListener);
                    break;
                default:
                    break;
            }
        }
    };

    private PlatActionListener mShareListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            Log.e("zp", "error:" + errorCode + ",msg:" + error);
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + error.getMessage() + "---" + errorCode;
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    public static SnsPlatform createSnsPlatform(String platformName) {
        String mShowWord = platformName;
        String mIcon = "";
        String mGrayIcon = "";
        String mKeyword = platformName;
        if (Wechat.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wechat";
            mGrayIcon = "jiguang_socialize_wechat";
            mShowWord = "jiguang_socialize_text_weixin_key";
        } else if (WechatMoments.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wxcircle";
            mGrayIcon = "jiguang_socialize_wxcircle";
            mShowWord = "jiguang_socialize_text_weixin_circle_key";

        } else if (WechatFavorite.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wxfavorite";
            mGrayIcon = "jiguang_socialize_wxfavorite";
            mShowWord = "jiguang_socialize_text_weixin_favorite_key";

        } else if (SinaWeibo.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_key";
        } else if (SinaWeiboMessage.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_msg_key";
        } else if (QQ.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_qq";
            mGrayIcon = "jiguang_socialize_qq";
            mShowWord = "jiguang_socialize_text_qq_key";

        } else if (QZone.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_qzone";
            mGrayIcon = "jiguang_socialize_qzone";
            mShowWord = "jiguang_socialize_text_qq_zone_key";
        } else if (Facebook.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_facebook";
            mGrayIcon = "jiguang_socialize_facebook";
            mShowWord = "jiguang_socialize_text_facebook_key";
        } else if (FbMessenger.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_messenger";
            mGrayIcon = "jiguang_socialize_messenger";
            mShowWord = "jiguang_socialize_text_messenger_key";
        }else if (Twitter.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_twitter";
            mGrayIcon = "jiguang_socialize_twitter";
            mShowWord = "jiguang_socialize_text_twitter_key";
        }
        return ShareBoard.createSnsPlatform(mShowWord, mKeyword, mIcon, mGrayIcon, 0);
    }

    private void permit() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().permit(id, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    text_top_right.setVisibility(View.VISIBLE);
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    text_top_right.setVisibility(View.GONE);
//                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
                }
            }
        });
    }
}
